package com.ruoyi.common.utils.wxgzh;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.ApiConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class WeChatAccessToken {

    @Autowired
    private static RedisTemplate<String,Object> redisTemplate;


    /**
     * 获取token
     * @return
     */
    public static String getAccessToken(){
        String access_token = (String)redisTemplate.opsForValue().get("blindbox:wx:accessToken");
        if(StringUtils.isEmpty(access_token)){
            String requestUrl= String.format(HttpUtils.sendGet(ApiConstants.accessTokenUrl,ApiConstants.GZH_APPID,ApiConstants.GZH_SECRET));
            JSONObject jsonObject = JSON.parseObject(HttpUtils.sendGet(requestUrl, ""));
            if (null != jsonObject && StringUtils.isNotEmpty(jsonObject.getString("access_token"))) {
                access_token = jsonObject.getString("access_token");
                String expires_in =jsonObject.getString("expires_in");  //留10分钟缓冲时间
                redisTemplate.opsForValue().set("blindbox:wx:accessToken",access_token,Long.parseLong(expires_in)-600,TimeUnit.SECONDS);
                return access_token;
            }else {
                return "";
            }
        }
        return access_token;
    }

    /**
     * 获取jsapi_ticket
     * @return
     */
    public static String getJsapiTicket(){
        System.out.println("+++++++++++++++++redisTemplate:"+ redisTemplate +"++++++++++++");
        String jsapiTicket = (String)redisTemplate.opsForValue().get("blindbox:wx:jsapiTicket");
        if(StringUtils.isEmpty(jsapiTicket)){
            String requestUrl =String.format(ApiConstants.jsapiTicketUrl,getAccessToken());
            JSONObject jsonObject = JSON.parseObject(HttpUtils.sendGet(requestUrl, ""));
            if (null != jsonObject && "0".equals(jsonObject.getString("errcode")) && StringUtils.isNotEmpty(jsonObject.getString("ticket"))) {
                jsapiTicket = jsonObject.getString("ticket");
                String expires_in = jsonObject.getString("expires_in");  //留10分钟缓冲时间
                redisTemplate.opsForValue().set("blindbox:wx:jsapiTicket",jsapiTicket,Long.parseLong(expires_in)-600,TimeUnit.SECONDS);
                return jsapiTicket;
            }else {
                return "";
            }
        }
        return jsapiTicket;
    }

}
